package cn.com.chengmandian.bike.controller.rent;


import cn.com.chengmandian.agent.utils.AuthUtil;
import cn.com.chengmandian.agent.utils.ServletUtil;
import cn.com.chengmandian.bike.dto.RentPenaltyPayForm;
import cn.com.chengmandian.bike.model.*;
import cn.com.chengmandian.bike.service.*;
import cn.com.chengmandian.bike.utils.AliPayUtil;
import cn.com.chengmandian.bike.utils.WxPayUtil;
import cn.com.chengmandian.core.web.pojo.AgentInfo;
import cn.com.chengmandian.core.web.pojo.AjaxResult;
import cn.com.chengmandian.core.web.utils.LocalMapUtil;
import cn.com.chengmandian.service.bike.BikePayClient;
import cn.com.chengmandian.service.bike.constants.ChannelTypeEnum;
import cn.com.chengmandian.service.bike.constants.MemberPayBusinessTypeEnum;
import cn.com.chengmandian.service.bike.constants.PayChannelEnum;
import cn.com.chengmandian.service.bike.form.BikePayForm;
import cn.hutool.core.util.StrUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;


/**
 * <p>
 * 电单车运营-分时租赁-罚金 前端控制器
 * </p>
 *
 * @author AutoGenerator
 * @since 2023-07-10
 */
@Api(tags = "分时租赁-罚金")
@RestController
@RequestMapping("/rent/penalty")
public class EbRentPenaltyController {

    @Autowired
    private IEbRentPenaltyService rentPenaltyService;
    @Autowired
    private IEbMemberWalletService memberWalletService;
    @Autowired
    private IEbMemberInfoService memberInfoService;
    @Autowired
    private IEbMemberPayService memberPayService;
    @Autowired
    private IEbRentOrderService rentOrderService;

    @Autowired
    private IEbAgentInfoService agentInfoService;

    @Autowired
    private IEbPayAccountService payAccountService;

    @Autowired
    private BikePayClient payClient;

    @ApiOperation("订单违约金")
    @GetMapping("/order/{orderId}")
    public AjaxResult<EbRentPenalty> order(@PathVariable("orderId") Integer orderId){
        return AjaxResult.success(rentPenaltyService.getByOrderId(orderId));
    }

    @ApiOperation("支付违约金")
    @PostMapping("/pay")
    public AjaxResult pay(@RequestBody RentPenaltyPayForm form) throws Exception{
        Assert.notNull(form.getPenaltyId(), "缺少违约金信息");
        Assert.notNull(form.getPayChannel(), "请选择充值渠道");

        EbRentPenalty ebRentPenalty = rentPenaltyService.getById(form.getPenaltyId());

        Integer memberId = AuthUtil.getAgentUser().getId();

        if (form.getPayChannel().equals(PayChannelEnum.WALLET.getCode())) {
            EbMemberWallet memberWallet = memberWalletService.getMemberWallet(memberId);
            if (memberWallet.getChargeMoney().compareTo(ebRentPenalty.getPayMoney()) < 0) {
                return AjaxResult.error("钱包充值余额不足");
            }
        }
        EbMemberInfo memberInfo = memberInfoService.getById(memberId);

        EbMemberPay memberPay = memberPayService.createPay(ebRentPenalty.getAreaId(), memberInfo.getId(), MemberPayBusinessTypeEnum.RENT_PENALTY_PAY, ebRentPenalty.getId(),
                ebRentPenalty.getPayMoney(), form.getPayChannel());

        rentPenaltyService.addPayRecord(ebRentPenalty.getId(), memberPay.getId(), memberPay.getPayNo());

        AgentInfo agentInfo = LocalMapUtil.getAgentInfo();

        EbAgentInfo info = agentInfoService.getById(agentInfo.getId());
        if (info.getPayAccountId() != null) {
            EbPayAccount payAccount = payAccountService.getPayAccount(info.getPayAccountId(), memberId);
            if (payAccount != null && (form.getPayChannel().equals(PayChannelEnum.WXPAY.getCode()) || form.getPayChannel().equals(PayChannelEnum.ALIPAY.getCode()))) {
                PayChannelEnum payChannel = PayChannelEnum.getByCode(form.getPayChannel());
                BikePayForm bikePayForm = new BikePayForm();
                bikePayForm.setMemberPayId(memberPay.getId());
                bikePayForm.setPayBusinessType(MemberPayBusinessTypeEnum.RENT_ORDER_PAY);
                bikePayForm.setPayChannel(payChannel);
                bikePayForm.setMoney(ebRentPenalty.getPayMoney());
                bikePayForm.setOpenId(StrUtil.isNotBlank(form.getOpenId()) ? form.getOpenId() : memberInfo.getOpenId());
                bikePayForm.setAlipayUserId(memberInfo.getAlipayUserId());
                bikePayForm.setAlipayOpenId(memberInfo.getAlipayOpenId());
                bikePayForm.setAreaId(agentInfo.getAreaId());
                bikePayForm.setMemberId(AuthUtil.getAgentUser().getId());
                bikePayForm.setBusinessId(ebRentPenalty.getId());
                bikePayForm.setClientIp(ServletUtil.getIp());
                return payClient.pay(agentInfo.getId(), bikePayForm);
            }
        }

        String notifyUrl = "http://"+ agentInfo.getDomain() + "/api/v1/bikeuser/notify/rent";

        if (form.getPayChannel().equals(PayChannelEnum.WXPAY.getCode())) {
            Assert.isTrue(StrUtil.isNotBlank(agentInfo.getWxMchId()), "未开启微信支付");
            if (form.getChannelType().equals(ChannelTypeEnum.MINI.getCode())) {
                String openId = StrUtil.isNotBlank(form.getOpenId()) ? form.getOpenId() : memberInfo.getOpenId();
                Assert.isTrue(StrUtil.isNotBlank(openId), "缺少openid");
                return AjaxResult.success(WxPayUtil.jsapiTransactions(
                        agentInfo.getWxMiniAppid(),
                        agentInfo.getWxMchId(),
                        openId,
                        "用户支付租赁违约金",
                        memberPay.getPayNo(),
                        memberPay.getMoney(),
                        agentInfo.getWxKeyPath(),
                        agentInfo.getWxCertPath(),
                        notifyUrl + "/wxpay/pay/" + LocalMapUtil.getAgentInfo().getId()
                ));
            }
        } else if (form.getPayChannel().equals(PayChannelEnum.ALIPAY.getCode())) {
            // 支付宝用户唯一标识user_id 和open_id必须有一个有值
            Assert.isTrue(StrUtil.isNotBlank(memberInfo.getAlipayUserId()) || StrUtil.isNotBlank(memberInfo.getAlipayOpenId()), "用户缺少支付宝用户标识");
            return AjaxResult.success(AliPayUtil.getTradeCreateRequestParam(
                    agentInfo.getAliMiniAppid(),
                    memberInfo.getAlipayUserId(),
                    memberInfo.getAlipayOpenId(),
                    "用户支付租赁违约金",
                    memberPay.getPayNo(),
                    memberPay.getMoney(),
                    agentInfo.getAliPayPrivateKey(),
                    agentInfo.getAliPayCertPath(),
                    agentInfo.getAliPayPublicCertPath(),
                    agentInfo.getAliPayRootCertPath(),
                    notifyUrl + "/ali/pay/" + LocalMapUtil.getAgentInfo().getId()
            ));
        } else if (form.getPayChannel().equals(PayChannelEnum.WALLET.getCode())) {
            rentOrderService.rentOrderPaySuccess(memberPay.getPayNo(), null);
            return AjaxResult.success("购买成功");
        }
        return AjaxResult.error("不支持的支付方式！");
    }
}
